/*  File Name	: MessageBlock.h
 *  Author		: Pang Jiacai
 *	 E-mail		: 823960168@qq.com
 *  Created on	: 2012-4-25
 *  Description: //写入时的字节顺序为小端格式（written in little endian）
 */

#ifndef MESSAGEBLOCK_H_
#define MESSAGEBLOCK_H_

#include <string.h>
#include <string>
#include "Define.h"

class MessageBlock
{
public:
	//size: this block space
	MessageBlock(int size=1024);

	virtual ~MessageBlock();

	//message block space
	int size(void) const;

	//block left space
	int left_size(void) const;

	void reset(void);

	void reset_rd_ptr(void);

	void reset_wr_ptr(void);

	char *base_ptr(void) const;

	//current write point
	char *wr_ptr(void) const;

	//current write point
	char *rd_ptr(void) const;

	//set read point
	void rd_ptr(int n);

	//set write point
	void wr_ptr(int n);

	void wr_len(int len);

	//the actually length written in this block
	int data_len(void);

	//free this block
	void release(void);

	/*
	 * copy data to this message block
	 * return 0 if success
	 * return -1 if block size less than
	 * 	@arg size or this block is unavailable
	 */
	int write(const char *buf,int size);

	/*
	 * copy block data to @arg buf
	 * return 0 if success
	 * return -1 if failed
	 */
	int read(const char *buf,int size);

	/*	ENDIAN_LITTLE=1,
	 * ENDDIAN_BIG=2
	 */
	static int endian(void);

	//overwrite operator "<<"
	MessageBlock & operator <<(const int &i);

	MessageBlock & operator <<(const unsigned int &ui);

	MessageBlock & operator <<(const short &s);

	MessageBlock & operator <<(const float &f);

	MessageBlock & operator <<(const double &d);

	MessageBlock & operator <<(const long &l);

	MessageBlock & operator <<(const long long &ll);

	MessageBlock & operator <<(const std::string &str);

	MessageBlock & operator <<(const char *buf);

	MessageBlock & operator <<(const char c);

	//overwrite operator ">>"
	MessageBlock & operator >>(const int &i);

	MessageBlock & operator >>(const unsigned int &ui);

	MessageBlock & operator >>(const short &s);

	MessageBlock & operator >>(const float &f);

	MessageBlock & operator >>(const double &d);

	MessageBlock & operator >>(const long &l);

	MessageBlock & operator >>(const long long &ll);

	MessageBlock & operator >>(std::string &str);

	MessageBlock & operator >>(const char &c);

private:
	MessageBlock &operator=(const MessageBlock &);

	MessageBlock(const MessageBlock &);

	char *base_ptr_;
	char *rd_ptr_;
	char *wr_ptr_;

	int size_;
	int left_size_;
	int wr_len_;

	int endian_;//本机的字节顺序
};

#endif /* MESSAGEBLOCK_H_ */
